/***************************************************************************
 *   Copyright (C) 2009 by Zheng Yonglei
 *   zhengyonglei@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "types.h"
#include "SQLiteDB.h"
#include "SelectListDialog.h"
#include "Logger.h"
#include "Options.h"

SelectListDialog::SelectListDialog(QDialog *parent)
    : QDialog(parent)
{
	ui.setupUi(this);

	QObject::connect(ui.closeSelectListDialogButton, SIGNAL(clicked()), this, SLOT(accept()));
}

SelectListDialog::~SelectListDialog()
{
}

int SelectListDialog::exec()
{
	OPT.setCursorBusy(true);
	ui.totalFinishedCountProgressBar->setValue(0);
	setListInfoTable();

	QString queryCommand;
	queryCommand = "select count(id) from test_records;";
	DB.execQuery(queryCommand, QueryT_Read, DB.curUsr);
	int totalWordsCount = DB.getTableValue(0, "count(id)").toInt();

	queryCommand = QString("select count(id) from test_records where test_state=%1; ").arg(TS_Finished);
	DB.execQuery(queryCommand, QueryT_Read, DB.curUsr);
	int finishedCount = DB.getTableValue(0, "count(id)").toInt();

	ui.totalFinishedCountProgressBar->setMinimum(1);
	ui.totalFinishedCountProgressBar->setMaximum(totalWordsCount);
	ui.totalFinishedCountProgressBar->setValue(finishedCount);

	QString statisticString = QString("Words Statistics: Total words:%1").arg(totalWordsCount);
	statisticString.append(QString("\tFinished Words:%1").arg(finishedCount));
	ui.wordStatisticsLabel->setText(statisticString);

	OPT.setCursorBusy(false);
	return QDialog::exec();
}

void SelectListDialog::setListInfoTable()
{
	QString queryCommand;
	QTextStream qs(&queryCommand);
	vector<int> listVec;
	map<int, int> totalCountMap;
	map<int, int> finishedCountMap;

	queryCommand.clear();
	qs	<<" select list "
		<<" from words "
		<<" group by list; ";
	DB.quickGet(queryCommand);
	for (int i=0; i<DB.getRowCount(); i++)
	{
		int listID = DB.getTableValue(i, "list").toInt();
		listVec.push_back(listID);
	}

	queryCommand.clear();
	qs	<<"select list,count(id) "
		<<"from words "
		<<"group by list;";
	DB.quickGet(queryCommand);
	for (int i=0; i<DB.getRowCount(); i++)
	{
		int listID = DB.getTableValue(i, "list").toInt();
		int wordCount = DB.getTableValue(i, "count(id)").toInt();
		totalCountMap[listID] = wordCount;
	}

	queryCommand.clear();
	qs<<	" select words.list,count(words.id) "
				" from words,test_records "
				" where "
				" words.id = test_records.id ";
	qs<<	" and test_records.test_state=" << TS_Finished;
	qs<<	" group by words.list; ";
	DB.quickGet(queryCommand);
	for (int i=0; i<DB.getRowCount(); i++)
	{
#ifdef Q_OS_WIN32
		int listID = DB.getTableValue(i, "words.list").toInt();
#else
		int listID = DB.getTableValue(i, "list").toInt();
#endif
		int wordCount = DB.getTableValue(i, "count(words.id)").toInt();
		finishedCountMap[listID] = wordCount;
	}

	QStringList headers;
	headers<<"List"<<"Test"<<"Browse"<<"Finished"<<"Total"<<"Progress";
	ui.listInfoTable->setColumnCount(headers.size());
	QList<float> sizeRate;
	sizeRate<<0.08<<0.08<<0.08<<0.08<<0.08<<0.45;
	float width = this->width();
	for (int i=0; i<sizeRate.size(); i++)
		ui.listInfoTable->setColumnWidth(i, sizeRate[i] * width);
	ui.listInfoTable->setHorizontalHeaderLabels(headers);
	ui.listInfoTable->setAlternatingRowColors(true);
	ui.listInfoTable->setSelectionMode(QAbstractItemView::NoSelection);

	ui.listInfoTable->setRowCount(totalCountMap.size());
	for (int i=0; i<listVec.size(); i++)
	{
		int finishedWordCount = 0;
		int wordCount = 0;
		int listID = listVec[i];

		map<int, int>::iterator it;
		it = totalCountMap.find(listID);
		if (it != totalCountMap.end())
			wordCount = it->second;

		it = finishedCountMap.find(listID);
		if (it != finishedCountMap.end())
			finishedWordCount = it->second;

		ui.listInfoTable->setItem(i, 0, new QTableWidgetItem(QString("list%1").arg(i+1, 2, 10, QChar('0'))));

		ListTableButton* testButton = new ListTableButton(i+1, TT_Test, tr("Test"));
		ui.listInfoTable->setCellWidget(i, 1, testButton);
		QObject::connect(testButton, SIGNAL(buttonClicked(int, TaskType)), this, SLOT(taskSelected(int, TaskType)));

		ListTableButton* browseButton = new ListTableButton(i+1, TT_Browse, tr("Browser"));
		ui.listInfoTable->setCellWidget(i, 2, browseButton);
		QObject::connect(browseButton, SIGNAL(buttonClicked(int, TaskType)), this, SLOT(taskSelected(int, TaskType)));

		ui.listInfoTable->setItem(i, 3, new QTableWidgetItem(QString("%1").arg(finishedWordCount)));
		ui.listInfoTable->setItem(i, 4, new QTableWidgetItem(QString("%1").arg(wordCount)));

		QProgressBar* progress = new QProgressBar(ui.listInfoTable);
		progress->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
		progress->setRange(0, wordCount);
		progress->setValue(finishedWordCount);
		ui.listInfoTable->setCellWidget(i, 5, progress);
	}
}

void SelectListDialog::taskSelected(int id, TaskType tt)
{
	LOG<<"ID="<<id<<"\ttt="<<tt<<endl;
	QString command;
	QTextStream qs(&command);

	qs<<"select id from words where words.list = "<<id<<";";
	DB.quickGet(command);
	QStringList testWordID;
	for (int i=0; i<DB.getRowCount(); i++)
		testWordID<<DB.getTableValue(i, "id");

	command = "update test_records set is_active=0; ";
	DB.quickUpdate(command);
	DB.quickUpdate("BEGIN");
	for (int i=0; i<testWordID.size(); i++)
	{
		command.clear();
		qs<<"update test_records set is_active=1 where id="<<testWordID[i];
		DB.quickUpdate(command);
	}
	DB.quickUpdate("COMMIT");
	this->done(tt);
}
